<template>
  <div class="app-container">
    <el-page-header class="pageHeader" :content="'当前所处：' + currentLocationName"
                    @back="goBack"></el-page-header>
    <el-divider></el-divider>
    <el-row :gutter="10" class="mb8" >
      <el-col :span="1.5" v-if="!isCreating">
        <el-button type="success" plain icon="el-icon-upload" size="mini" @click="addFile">上传文件</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!isCreating">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addFolder">新建文件夹</el-button>
      </el-col>
      <el-col :span="1.5" >
        <el-button plain icon="el-icon-refresh" size="mini" @click="refreshGetList">刷新</el-button>
      </el-col>
    </el-row>
    <!-- 文件浏览区 -->
    <div style="overflow: hidden;">
      <el-row :gutter="20" :span="6">
<!--        <el-col :span="4">
          <div v-if="!isCreating" class="drawing_card" style="height:60vh">
            <el-tree accordion :data="treeData"
              node-key="id"
              draggable
              ref="tree"
              :default-expand-all="true"
              highlight-current>
            </el-tree>
          </div>
        </el-col>-->
        <el-col>
          <el-row :span="18">
            <el-card class="drawing_card" v-loading="cardLoading" style="height: 60vh">
              <template v-if="fileAndFolderList.length === 0">
                <el-empty description="暂无文件，请创建一个文件夹吧" style="height:60vh"></el-empty>
              </template>
              <!-- 文件夹和文件的显示 -->
              <el-checkbox :indeterminate="isIndeterminate"
                           v-model="checkAll"
                           @change="handleCheckAllChange" >全选</el-checkbox>
              <div class="items-list">
                <el-checkbox v-for="(item, index) in fileAndFolderList"
                             v-model="item.selected"
                             :key="index" @change="handleItemCheckedChange(item)" class="folder-checkbox">
                  <div v-if="item.type == 0 ">
                    <div class="folderContainer">
                      <div class="folderWrapper"  @dblclick="doubleClickFolder(index, item)"
                           @contextmenu.prevent.stop="rightClickFolder(index, item, $event)">
                        <img alt="item.folderName" src="@/assets/images/folder.png" style="width: 100px;height: 90px;margin-top: -13px"
                             @contextmenu.prevent.stop="rightClickFolder(index, item, $event)" />
                        <div class="folderName">
                              <span>{{
                                  item.folderName.length > 10 && item.folderName !=null ?
                                    item.folderName.substring(0, 6) + '...' : item.folderName
                                }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <div class="folderContainer">
                      <div class="folderWrapper" @dblclick="doubleClickFolder(index,item)">
                        <img src="@/assets/images/fileImg.png" style="width: 100px;height: 90px;margin-top: -13px"
                             @contextmenu.prevent.stop="rightClickfile(index, item, $event)" />
                        <div class="folderName">
                            <span>{{
                                item.fileName.length > 10  && item.fileName !=null ?
                                  item.fileName.substring(0, 6) + '...' : item.fileName
                              }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-checkbox>
              </div>
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <!-- 右键 空白处 -->
    <div class="add-folder-9" :style="folderStyle" v-show="folderShow">
      <div class="add-folder-1">
        <div class="add-folder-2" @click="addFile">
          上传文件
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="addFolder">
          新建目录
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="refreshGetList">
          刷新
        </div>
      </div>
    </div>
    <!-- 文件夹【右键菜单】 -->
    <div class="add-folder-9" :style="folderStyle" v-show="folderShow">
      <div class="add-folder-1">
        <div class="add-folder-2" @click="openFolder">
          打开文件夹
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="moveFolder">
          移动
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="updateFloder">
          重命名
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-6" @click="deleteFolderFun">
          删 除
        </div>
      </div>
    </div>
    <!-- 文件【右键菜单】 -->
    <div class="add-folder-9" :style="fileStyle" v-show="fileShow">
      <div class="add-folder-1">
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="updateFileFun">
          重命名
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-2" @click="moveFolder">
          移动
        </div>
        <div style="border: 2px solid rgba(18,17,42,.07)"></div>
        <div class="add-folder-6" @click="deleteFileFun">
          删 除
        </div>
      </div>
    </div>
    <!-- 上传文件 弹窗 -->
    <addFolder ref="addFolder1" :currentLocationId="currentLocationId" :currentLocationName="currentLocationName"/>
    <moveFolder ref="moveFolder1" :moveData="moveData"></moveFolder>

    <!--视频预览-->
    <el-dialog :visible.sync="showPreview"
               :destroy-on-close="true"
               width="60%"
               :show-close="true"
               @closed="handleDialogClose">
       <vue-core-video-player
          ref="videoPlayer"
          :title="videoTitle"
          :playsinline="true"
          :src="videoUrl"
          style="height: 600px">
       </vue-core-video-player>

    </el-dialog>

  </div>
</template>

<script>

import addFolder from './addFolder.vue'
import moveFolder from './moveFolder.vue'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { queryFileList , createPublicFolder, renameFolder, deleteFolder, deleteFile } from '@/api/tuike/folder';

export default {
  name: 'shareSpace',
  components: {addFolder, moveFolder, Treeselect },
  props: {
    isCreating: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
        historyFolderId: 0,//历史文件夹id，用于【返回上一级】
        historyFolderName: null,//历史文件夹name，用于【返回上一级】

        currentLocationId: 0,//当前所处位置（文件夹）id，0为根目录
        currentLocationName: '素材文件管理',//当前所处位置（文件夹）名

        //移动文件（夹）时需要的参数
        moveData: {
          typeofFolder: 0,//所选对象的类型（1：文件夹；2：文件）
          clickFolderId: -1,//被右键的文件夹id
        },

        cardLoading: true,
        // 文件夹 右键菜单栏
        folderStyle: {
          left: '0px',
          top: '0px'
        },
        folderShow: false,
        clickFolderId: -1,//被右键的文件夹id
        clickFolderName: '',//被右键的文件夹名
        // 文件 右键菜单栏
        fileStyle: {
          left: '0px',
          top: '0px'
        },
        fileShow: false,
        clickFileId: -1,//被右键的文件id
        clickFileName: '',//被右键的文件名
        clickFilePath: '',//被右键的文件路径-已加上下载的路径网站前端
        queryParams: {  //查询参数
          folderId: 0 ,//目标文件（夹）id，值为0则查询根目录文件（夹）
          parentId: 0
        },
        treeData: [{
              id: 1,
              label: '根',
              children: [{
                  id: 2,
                  label: 'folder1',
                  children: [{
                    id: 4,
                    label: 'folder'
                  }]
                },
                {
                  id: 3,
                  label:'text.txt'
                }
              ]
            }
        ],
        checkAll:false,
        isIndeterminate:true,
        checkedFilesList: [],
        fileAndFolderList:[],
        showPreview:false,
        videoUrl:"",
        videoTitle:""
      }
    } ,
  methods: {
    // 多选框逻辑
    handleCheckAllChange(val) {
      // 当点击全选时，设置所有项目的选中状态为全选的状态
      this.fileAndFolderList.forEach(item => {
        item.selected = val;
      });
      // 确保部分选中状态取消
      this.isIndeterminate = false;

    },
    handleDialogClose(){
      this.$refs.videoPlayer.pause();
      this.showPreview =false;
    },
    // 当单个复选框状态变化时，处理是否更新全选和部分选中状态
    handleItemCheckedChange(item) {
      //item.selected = !item.selected;
      const checkedCount = this.fileAndFolderList.filter(item => item.selected).length;

      // 如果选中的数量和总数量相同，设置全选为 true
      this.checkAll = checkedCount === this.fileAndFolderList.length;

      // 如果有部分选中且没有全选，设置为部分选中状态
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.fileAndFolderList.length;
    },

    //返回上一级
    goBack() {
      if (this.currentLocationId == 0) {
        this.$message({
          message: '已经不能再往后退啦！',
          type: 'warning'
        });
      } else {
        this.queryParams.folderId = this.historyFolderId;
        this.queryParams.parentId = this.historyFolderId;

        this.currentLocationId = this.historyFolderId;
        this.currentLocationName = this.historyFolderName == null ? '素材文件管理' : this.historyFolderName;

        this.historyFolderId = this.currentLocationId;
        this.historyFolderName = this.currentLocationName;
        this.getList();
      }

    },
    // 获取列表数据
    getList() {
      this.cardLoading = true;
      queryFileList(this.queryParams).then(response => {
        this.distributeList = this.handleTree(response.data, "id", "parentId");
        this.fileAndFolderList = response.data;
        this.cardLoading = false;
        this.checkedFilesList = this.fileAndFolderList;
      })
    },
      /** 转换fileUpload数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.fileName,
        children: node.children
      };
    },
    // 刷新当前列表
    refreshGetList() {
      this.queryParams.folderId = this.currentLocationId;
      this.getList()
      this.initClickId()
    },

    //上传文件
    addFile() {
      this.$refs.addFolder1.open();
    },

    //创建文件夹
    addFolder() {

      this.$prompt('请输入新文件夹名称', '创建文件夹', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        let createdFolder = {
          folderName: value,
          parentId: this.currentLocationId
        }
        createPublicFolder(createdFolder).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '创建成功 '
            });
            const that = this;
            setTimeout(function () {
              that.refreshGetList();  // 刷新当前页面
            }, 500);

          } else {
            this.$message({
              type: 'error',
              message: '创建失败 '
            });
          }
        })

      }).catch(() => {
      });
    },
    // 重命名文件夹
    updateFloder() {
      this.folderShow = false;
      this.$prompt('请输入文件夹的新名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.clickFolderName,
        inputErrorMessage: '输入不能为空',
        inputValidator: (value) => {       // 点击按钮时，对文本框里面的值进行验证
          if (!value) {
            return '输入不能为空';
          }
        },
      }).then(({ value }) => {
        let sysFolder = {
          folderName: value,
          folderId: this.clickFolderId,
          type: 0, // 1 for file , 0 for folder
        }
        renameFolder(sysFolder).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '修改成功 '
            });
            let that = this;
            setTimeout(function () {
              that.refreshGetList();  // 刷新当前页面
            }, 500);

          } else {
            this.$message({
              type: 'error',
              message: '修改失败 '
            });
          }
        })

      })
    },
    //删除文件夹
    deleteFolderFun() {
      this.folderShow = false;
      this.$confirm('此操作将永久删除该文件夹，包括文件夹内的所有内容，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          folderId : this.clickFolderId,
          type:0
        }
        deleteFolder(data).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功 '
            });
            let that = this;
            setTimeout(function () {
              that.refreshGetList();  // 刷新当前页面
            }, 1000);

          } else {
            this.$message({
              type: 'error',
              message: '删除失败！ '
            });
          }
        })

      })
    },
    //打开文件夹
    openFolder() {
      this.folderShow = false;
      this.queryParams.folderId = this.clickFolderId;
      this.queryParams.parentId = this.clickFolderId;

      this.currentLocationId = this.clickFolderId;
      this.currentLocationName = this.clickFolderName;
      this.getList();


    },
    //鼠标双击文件夹
    doubleClickFolder(index, item) {
      if (item.type == 0) {
        this.openFolder();
        this.clickFolderId = item.folderId;
        this.clickFolderName = item.folderName;
      }else {
          this.videoTitle = item.fileName.split(".")[0]
          this.videoUrl = item.fileUrl;
          this.showPreview = true;
      }
    },
    //文件夹右键
    rightClickFolder(index, item, e) {

      this.initClickId()
      this.clickFolderName = item.folderName
      this.clickFolderId = item.folderId
      this.folderStyle.left = e.pageX - 140 + 'px'
      this.folderStyle.top = e.pageY - 70 + 'px'
      this.folderShow = true
      this.moveData.typeofFolder = 1


    },
    //文件 右键
    rightClickfile(index, item, e) {
      this.initClickId()
      // this.clickFilePath = "https://huang-pu.oss-cn-guangzhou.aliyuncs.com/" + item.filePath
      this.fileStyle.left = e.pageX - 140 + 'px'
      this.fileStyle.top = e.pageY - 70 + 'px'
      this.fileShow = true
      this.clickFileId = item.fileId
      this.clickFileName = item.fileName

      this.moveData.typeofFolder = 2
    },
    // 重命名文件
    updateFileFun() {
      this.fileShow = false;
      this.$prompt('请输入文件的新名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.clickFolderName,
        inputErrorMessage: '输入不能为空',
        inputValidator: (value) => {       // 点击按钮时，对文本框里面的值进行验证

          if (!value) {
            return '输入不能为空';
          }
          if(value.split("\\.").length>2){
            this.$message({
              type: 'error',
              message: '不需要后缀名'
            });
            return;
          };
        },
      }).then(({ value }) => {
        let renameFile = {
          folderName: value,
          folderId:  this.clickFileId,
          type: 1, // 1 for file , 0 for folder
        }
        renameFolder(renameFile).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '修改成功 '
            });
            let that = this;
            setTimeout(function () {
              that.refreshGetList();  // 刷新当前页面
            }, 500);

          } else {
            this.$message({
              type: 'error',
              message: '修改失败 '
            });
          }
        })
      })
    },

    //删除文件
    deleteFileFun() {
      this.fileShow = false;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          folderId : this.clickFileId,
          type:1
        }
        deleteFolder(data).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功 '
            });
            let that = this;
            setTimeout(function () {
              that.refreshGetList();  // 刷新当前页面
            }, 1000);

          } else {
            this.$message({
              type: 'error',
              message: '删除失败！ '
            });
          }
        })

      })

    },

    //移动文件(夹)
    moveFolder() {
      this.fileShow = false
      //通过判断文件/文件夹被右键选择而进行参数存储freshTable
      if (this.clickFolderId != -1) {
        this.moveData.clickFolderId = this.clickFolderId;
      } else {
        this.moveData.clickFolderId = this.clickFileId;
      }

      this.$refs.moveFolder1.open();
    },

    //初始化右键选择相关参数
    initClickId() {
      this.clickFileId = -1;
      this.clickFolderId = -1;
      this.fileShow = false;
      this.folderShow = false;
    },
  },
  mounted() {
    //监听鼠标点击事件
    document.addEventListener("click", (e) => {
      if (!this.folderShow && !this.fileShow) return; // 如果右键菜单不显示，则不处理点击事件
      let target = e.target;
      while (target && target.parentNode) {
        if (target.parentNode.class === "folderContainer") {
          return;
        }
        target = target.parentNode;
      }
      this.folderShow = false;
      this.fileShow = false; // 如果点击的是其他区域，则隐藏
      this.clickFolderId = -1;
      this.clickFileId = -1;
    });
  },

  created() {
    this.getList()
  },

  handleNodeClick(){
    console.log("click on node...")
  }
}
</script>

<style lang="scss">
  .pageHeader {
    .el-page-header__content {
      font-size: 16px !important;
    }
  }
  .drawing_card {
    width: 100%;
    height: 100%;
    float: left;
    margin-top: 15px;
    overflow: auto;
    box-shadow: 0 5px 5px rgb(0 0 0 /10%);
    transition: all 0.9s;
    border-radius: 10px;
  }
  .folder-checkbox{
    margin-top: 10px;
    .el-checkbox__input{
      margin-right: -20px;
      margin-top: -30px;
    }
  }
  .folderContainer {
    width: 150px;
    float: left;
    display: block;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
    margin-left: 0px;
    margin-top:10px;
  }


  .folder {
    width: 110px;
    height: 80px;
    perspective: 600px;
    transform-style: preserve-3d;
    cursor: pointer;
  }

  .folderWrapper {
    width: 140px;
    height: 130px;
    padding: 20px 20px 10px 20px;
    position: relative;
    transition: all .2s ease;
    border-radius: 6px;
    cursor: pointer;
  }

  .folderWrapper:hover {
    background-color: aliceblue;
  }


  .folderName {
    margin-top: 5px;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    width: 100px;
  }


  .add-folder-9 {
    position: absolute;
    display: flex;
    justify-content: center;
    padding: 2px;
    align-items: center;
    width: 130px;
    background-color: rgba(6, 13, 20, .18);
    border-radius: 12px;
    z-index: 99999;
    box-shadow: 0px 8px 24px rgba(25, 25, 26, .06), 0px 4px 16px rgba(25, 25, 26, .04), 0px 0px 4px rgba(25, 25, 26, .04);
  }

  .add-folder-1 {
    overflow: hidden;
    width: 97%;
    height: 96%;
    background-color: #fff;
    border-radius: 10px;
  }

  .add-folder-2 {
    color: #19191a;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 36px;
    // margin-top: 5px;
    // margin-bottom: 5px
  }

  .add-folder-2:hover {
    background-color: rgba(6, 13, 20, .18);
    // border-radius: 10px;
    cursor: pointer;
  }

  .add-folder-6 {
    color: #19191a;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 36px;
    // margin-top: 5px;
  }

  .add-folder-6:hover {
    background-color: red;
    // border-radius: 10px;
    cursor: pointer;
  }
</style>

